package tech.wetech.admin3.util;

import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

@Component
public class HashUtil {
  public String getFileHash(MultipartFile file) {
    try {
      // 计算文件的哈希值
      MessageDigest md = MessageDigest.getInstance("SHA-256");
      md.update(file.getBytes());
      byte[] hashBytes = md.digest();   // 计算字节流的MD5哈希值
      StringBuilder sb = new StringBuilder();
      for (byte b : hashBytes) {
        sb.append(String.format("%02x", b));    // 将哈希值转换为16进制字符串
      }
      String hashValue = sb.toString();
      // 将哈希值存储到数据库中
      return hashValue;
    } catch (NoSuchAlgorithmException e) {
      e.printStackTrace();  // 异常处理：没有该算法时抛出
    } catch (IOException e) {
      e.printStackTrace();  // 异常处理：获取字节流时出现IO异常
    }
    return null;
  }

  public String getStringHash(String s) {
    try {
      // 获取MessageDigest的实例，并指定哈希算法名称
      MessageDigest digest = MessageDigest.getInstance("SHA-256");

      // 对字符串进行编码，并计算哈希值
      byte[] encodedhash = digest.digest(s.getBytes("UTF-8"));

      // 将哈希值转换为十六进制字符串
      StringBuilder hexString = new StringBuilder();
      for (byte b : encodedhash) {
        String hex = Integer.toHexString(0xff & b);
        if (hex.length() == 1) hexString.append('0');
        hexString.append(hex);
      }
      return hexString.toString();

    } catch (Exception e) {
      System.err.println("An error occurred: " + e.getMessage());
      return null;
    }
  }
}

